package com.example.viewpager2demo

import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class MainActivity : AppCompatActivity() {
    private lateinit var viewPager: ViewPager2
    private lateinit var tabLayout: TabLayout
    private lateinit var adapter: PageAdapter
    private var pageCount = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewPager = findViewById(R.id.viewPager)
        tabLayout = findViewById(R.id.tabLayout)
        adapter = PageAdapter(this)
        adapter.setTabLayout(tabLayout)
        viewPager.adapter = adapter

        // 设置TabLayout和ViewPager2的联动
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = "页面 ${position + 1}"
        }.attach()

        findViewById<Button>(R.id.btnAddFragment).setOnClickListener {
            addNewFragment()
        }

        findViewById<Button>(R.id.btnDeleteFragment).setOnClickListener {
            deleteCurrentFragment()
        }

        // 添加初始页面
        addNewFragment()
    }

    private fun addNewFragment() {
        adapter.addFragment(PageFragment.newInstance(pageCount++))
        viewPager.currentItem = pageCount - 1
        // 更新TabLayout
        tabLayout.getTabAt(pageCount - 1)?.select()
    }

    private fun deleteCurrentFragment() {
        val currentPosition = viewPager.currentItem
        if (adapter.itemCount > 1) {
            adapter.removeFragment(currentPosition)
            // 如果删除的是最后一个页面，需要调整当前页面位置
            if (currentPosition == adapter.itemCount) {
                viewPager.currentItem = adapter.itemCount - 1
                tabLayout.getTabAt(adapter.itemCount - 1)?.select()
            }
        } else {
            Toast.makeText(this, "至少保留一个页面", Toast.LENGTH_SHORT).show()
        }
    }
}